#include "topic.h"

QString User::getProperty(QString name) const{
    return properties.value(name);
}

void User::setProperty(QString name, QString property){
    properties.insert(name, property);
}

QString Article::display(){
    QString val(tr("Sender : %1 (%2)\t From : %3\nTitle : %4\nPost Time : %5\n%6\n--\n%7\n"));
    return val.arg(author->getProperty("id"))
    .arg(author->getProperty("nick"))
    .arg(board)
    .arg(title)
    .arg(time)
    .arg(content)
    .arg(signature);
}

QString Article::reply(){
    return tr("\n[QUOTE:]")+ content;
}

bool Topic::addArticle (Article * article){
    bool ret = true;
    int i = articlePool.count();
    while ( i -- > 0){
	if (article->id == articlePool[i]->id)
	    break;
    }
    if (i == -1){
	articlePool << article;
// 	profile->notice(article);
    }
    else
	ret =  false;
    return ret;
}

Topic::~Topic(){
    int i = articlePool.count();
    while ( i -- > 0)
	delete articlePool[i];
    articlePool.clear();
}

Topic::Topic(QString boardId , QString newId , QString newName , int newReply )
:board(boardId) , id(newId) , name(newName) , reply(newReply){
    favorite = false;
}

QString Topic::display(){
    return name;
}

// defines for the topic list model
topicModel::topicModel(QObject *parent) : QAbstractListModel(parent), topic(0) {}

QVariant topicModel::data(const QModelIndex &index, int role) const{
    if (!index.isValid() || topic == 0)
	return QVariant();
    if (index.row() >= topic->articlePool.count())
	return QVariant();
    if (role == Qt::DisplayRole)
	return topic->articlePool.value(index.row())->display();
    else
	return QVariant();
}

int topicModel::rowCount(const QModelIndex &) const{
    return (!topic)?0:topic->articlePool.count();
}

//允许 setTopic(0)
void topicModel::setTopic(Topic * newTopic){
    if (topic != 0)
	disconnect(&gFastTimer, SIGNAL(timeout()), topic, SLOT(refreshMe()));
    topic = newTopic;
    if (topic == 0)
	return;
    connect(&gFastTimer, SIGNAL(timeout()), topic, SLOT(refreshMe()));
    connect(topic, SIGNAL(refreshFinished(bool)), this, SLOT(refresh(bool)));
    topic->refreshMe();
}

void topicModel::refresh(bool){
    DEBUG_F();
    reset();
}

QModelIndex topicModel::index(int row, int column, const QModelIndex &parent) const{
    if (parent.isValid() || topic == 0 || row < 0)
	return QModelIndex();
    
    if (row >= topic->articlePool.count())
	return QModelIndex();
    
    Article * article = topic->articlePool.value(row);
    return createIndex(row, column, article);
}
